package com.xy.servlet;

import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 谢阳
 * @version 1.8.0_131
 * @date 2022/4/11 12:33
 * @description
 */


@WebServlet(value = "/async",asyncSupported = true)
public class HelloAsyncServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //super.doGet(req, resp);
        System.out.println(Thread.currentThread() + "主线程start...");

        // 1、开启异步处理 asyncSupported = true

        // 2、开启异步模式
        AsyncContext asyncContext = req.startAsync();

        // 3、 业务异步处理，开始异步处理
        asyncContext.start(() -> {
            try {
                sayHello();
                asyncContext.complete();
                asyncContext.getResponse().getWriter().write("hello...");
                System.out.println(Thread.currentThread() + "hello...");
            } catch (InterruptedException | IOException e) {
                e.printStackTrace();
            }
        });
        System.out.println(Thread.currentThread() + "主线程end...");
    }


    public void sayHello() throws InterruptedException {
        System.out.println(Thread.currentThread() + "processing...");

        Thread.sleep(3000);
    }
}
